﻿using RuYiAdmin.Net.Common.CommonClass.Excel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace RuYiAdmin.Net.Common.CommonClass.Extensions
{
    /// <summary>
    /// List导出拓展类
    /// </summary>
    public static class ListExport
    {
        /// <summary>
        /// 导出字典集
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="list">集合</param>
        /// <returns>字典集</returns>
        public static List<Dictionary<String, Object>> Export<T>(this List<T> list)
        {
            var dictionaryList = new List<Dictionary<String, Object>>();

            //遍历元素
            foreach (var item in list)
            {
                //元素属性
                var properties = item.GetType().GetProperties();

                var dictionary = new Dictionary<String, Object>();

                //遍历元素的属性
                foreach (var property in properties)
                {
                    if (!property.IsDefined(typeof(ExcelExportAttribute), false))
                    {
                        continue;
                    }

                    //元素Custom Attribute
                    var attributes = property.GetCustomAttributes();

                    //遍历元素的Custom Attribute
                    foreach (var attribute in attributes)
                    {
                        if (attribute.GetType().Equals(typeof(ExcelExportAttribute)))
                        {
                            //列名
                            var columnName = ((ExcelExportAttribute)attribute).ColumnName;

                            //列值
                            var columnValue = item.GetType().GetProperty(property.Name).GetValue(item);

                            //添加到字典
                            dictionary.Add(columnName, columnValue);

                            break;
                        }
                    }
                }

                dictionaryList.Add(dictionary);
            }

            return dictionaryList;
        }
    }
}
